package com.superhelper.app.controller;

import java.io.BufferedReader;
import java.io.IOException;
import java.util.Date;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import com.pingplusplus.model.Charge;
import com.pingplusplus.model.Event;
import com.pingplusplus.model.EventData;
import com.pingplusplus.model.PingppObject;
import com.pingplusplus.model.Webhooks;
import com.superhelper.app.controller.base.AbstractController;
import com.superhelper.app.service.PayService;
import com.superhelper.app.utils.WebHooksVerify;

/**
 * 
 */
@Controller
@RequestMapping("/notify")
public class PingNotifyController extends AbstractController {

    @Autowired
    private PayService payService;

    @RequestMapping("/ping")
    public void recharge(HttpServletRequest request, HttpServletResponse response) throws IOException {
        request.setCharacterEncoding("UTF8");
        // 获得 http body 内容
        BufferedReader reader = request.getReader();
        StringBuffer buffer = new StringBuffer();
        String string;
        while ((string = reader.readLine()) != null) {
            buffer.append(string);
        }
        reader.close();
        String sign = request.getHeader("x-pingplusplus-signature");
        // 解析异步通知数据
        String ev = buffer.toString();
        boolean verifyResult = false;

        try {
            verifyResult = WebHooksVerify.verify(ev, sign);
        } catch (Exception e) {
            log.error("verify error,ev:{},sign:{}", ev, sign, e);
        }
        log.info("verify ev:{}, result:{}", ev, verifyResult);
        if (!verifyResult) {
            // 验证不通过
            response.setStatus(500);
        } else {
            Event event = Webhooks.eventParse(ev);

            if ("charge.succeeded".equals(event.getType())) {
                try {
                    EventData data = event.getData();
                    PingppObject obj = data.getObject();
                    if (obj instanceof Charge) {

                        Charge charge = (Charge) obj;
                        String dealNo = charge.getOrderNo();
                        Long payt = charge.getTimePaid();
                        String payDealNo = charge.getTransactionNo();
                        Date payTime = new Date(payt * 1000);

                        boolean result = StringUtils.isBlank(dealNo) ? false : payService.paySuccess(dealNo, payDealNo,
                                payTime);
                        log.info("[notify/ping] orderNo:{},payTime:{},payDealNo:{},result:{}", dealNo, payTime,
                                payDealNo, result);
                        if (result) {
                            // sendMsg(dealNo);
                            response.setStatus(200);
                        } else {
                            response.setStatus(500);
                        }
                    } else {
                        response.setStatus(500);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            } else if ("refund.succeeded".equals(event.getType())) {
                response.setStatus(200);
            } else {
                log.info("[notify/ping] unkown envet type:{}", event.getType());
                response.setStatus(500);
            }
        }
    }

    /**
     * 消息通知
     * 
     * @param dealNo
     */
    private void sendMsg(final String dealNo) {

        threadPool.submit(new Runnable() {

            @Override
            public void run() {
                // TODO Auto-generated method stub

            }
        });
    }
}